# -*- coding: utf-8 -*-
# PySide6使用元对象调用槽函数
# keywords : QMetaObject,元对象系统,QMetaObject.invokeMethod


import sys
from PySide6.QtCore import QObject, QMetaObject, QMetaMethod, Slot,Qt,Q_ARG
from PySide6.QtWidgets import QApplication


class MyObject(QObject):
    def __init__(self):
        super().__init__()

    @Slot(int)
    def my_method(self, value):
        print(f"Received value: {value}")


if __name__ == '__main__':
    app = QApplication(sys.argv)

    # 创建对象实例
    obj = MyObject()

    # 获取对象的 QMetaObject
    meta_object = obj.metaObject()

    # 查找方法的索引
    method_index = meta_object.indexOfMethod("my_method(int)")
    if method_index != -1:
        # 获取方法对象
        method = meta_object.method(method_index)

        # 使用 QMetaObject::invokeMethod 调用方法
        success = QMetaObject.invokeMethod(obj, "my_method", Qt.QueuedConnection, Q_ARG(int, 42))
        if success:
            print("Method called successfully.")
        else:
            print("Failed to call the method.")
    else:
        print("Method not found.")

    sys.exit(app.exec())